package com.pond.pond.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pond.common.core.domain.R;
import com.pond.common.core.utils.DateUtils;
import com.pond.common.core.utils.StringUtils;
import com.pond.common.core.web.domain.AjaxResult;
import com.pond.pond.domain.Appointment;
import com.pond.pond.domain.AppointmentTimeSegment;
import com.pond.pond.domain.PondOrder;
import com.pond.pond.domain.PondOrderItem;
import com.pond.pond.domain.PondSeat;
import com.pond.pond.domain.dto.CreateOrderRequest;
import com.pond.pond.domain.dto.OrderQueryRequest;
import com.pond.pond.domain.vo.OrderVO;
import com.pond.pond.mapper.*;
import com.pond.pond.service.IPondOrderService;

import java.math.BigDecimal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pond.system.api.RemoteUserService;
import com.pond.common.core.constant.SecurityConstants;
import com.pond.system.api.model.LoginUser;
import com.pond.system.api.domain.SysUser;
import com.pond.system.api.domain.SysDept;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单服务实现类
 */
@Service
public class PondOrderServiceImpl implements IPondOrderService {
    
    @Autowired
    private PondOrderMapper pondOrderMapper;
    
    @Autowired
    private PondOrderItemMapper pondOrderItemMapper;
    
    @Autowired
    private RemoteUserService remoteUserService;
    
    @Autowired
    private AppointmentMapper appointmentMapper;
    
    @Autowired
    private AppointmentTimeSegmentMapper appointmentTimeSegmentMapper;
    
    @Autowired
    private PondMapper pondMapper;
    
    @Autowired
    private PondSeatMapper pondSeatMapper;
    
    // 订单编号生成器（移除静态计数器，改用数据库查询）
    
    @Override
    @Transactional
    public AjaxResult createOrderFromAppointment(Long appointmentSegmentId) {
        try {
            // 1. 查询预约时间段信息
            AppointmentTimeSegment timeSegment = appointmentTimeSegmentMapper.selectById(appointmentSegmentId);
            if (timeSegment == null) {
                return AjaxResult.error("预约时间段不存在");
            }
            
            // 2. 查询预约信息
            Appointment appointment = appointmentMapper.selectAppointmentById(timeSegment.getAppointmentId());
            if (appointment == null) {
                return AjaxResult.error("预约信息不存在");
            }
            
            // 3. 检查预约状态（必须是已签到状态）
            if (timeSegment.getStatus() != 1) {
                return AjaxResult.error("预约未签到，无法创建订单");
            }
            
            // 4. 检查是否已经创建过订单
            PondOrder existingOrder = pondOrderMapper.selectByAppointmentSegmentId(appointmentSegmentId);
            if (existingOrder != null) {
                return AjaxResult.error("该预约已创建订单，订单编号：" + existingOrder.getOrderNo());
            }
            
            // 5. 创建订单（带重试机制）
            PondOrder order = new PondOrder();
            order.setUserId(appointment.getUserId());
            order.setDeptId(appointment.getDeptId());
            order.setPondId(appointment.getPondId());
            order.setSeatId(timeSegment.getSeatId()); // 设置钓位ID
            order.setOrderType(1); // 1-预约订单
            order.setStartTime(new Date()); // 设置开始时间为当前时间
            order.setAppointmentSegmentId(appointmentSegmentId);
            order.setStatus(0); // 未完成
            order.setTotalAmount(0.0);
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setDelFlag(0);
            
            int result = 0;
            // 最多尝试3次插入订单
            for (int retry = 1; retry <= 3; retry++) {
                try {
                    order.setOrderNo(generateOrderNo());
                    result = pondOrderMapper.insertPondOrder(order);
                    if (result > 0) {
                        System.out.println("订单创建成功，订单编号: " + order.getOrderNo() + " (尝试第" + retry + "次)");
                        break;
                    }
                } catch (Exception e) {
                    if (e.getMessage().contains("Duplicate entry") && retry < 3) {
                        System.out.println("订单编号重复，重试第" + retry + "次: " + e.getMessage());
                        continue;
                    } else {
                        throw e;
                    }
                }
            }
            if (result > 0) {
                // 6. 创建默认钓费项目
                createDefaultFeeItem(order.getId(), timeSegment.getSeatId());
                
                // 7. 更新订单总金额
                updateOrderTotalAmount(order.getId());
                
                // 8. 更新预约时间段状态为"管理员确认签到"
                timeSegment.setStatus(5); // 5 - 管理员确认签到
                appointmentTimeSegmentMapper.updateById(timeSegment);
                System.out.println("预约时间段状态已更新为管理员确认签到 - 时间段ID: " + appointmentSegmentId);
                
                return AjaxResult.success("订单创建成功", order.getOrderNo());
            } else {
                return AjaxResult.error("订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("订单创建异常：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public AjaxResult createOrderDirect(CreateOrderRequest request) {
        try {
            // 打印接收到的请求数据
            System.out.println("=== 创建订单请求数据 ===");
            System.out.println("用户类型: " + request.getUserType());
            System.out.println("用户ID: " + request.getUserId());
            System.out.println("用户姓名: " + request.getUserName());
            System.out.println("用户手机号: " + request.getUserPhone());
            System.out.println("钓场ID: " + request.getDeptId());
            System.out.println("鱼塘ID: " + request.getPondId());
            System.out.println("钓位ID: " + request.getSeatId());
            System.out.println("开始时间: " + request.getStartTime());
            System.out.println("预约时间段ID: " + request.getAppointmentSegmentId());
            System.out.println("备注: " + request.getRemark());
            
            // 1. 参数验证
            if (request.getDeptId() == null) {
                return AjaxResult.error("钓场ID不能为空");
            }
            
            Long userId = null;
            
            // 2. 根据用户类型处理用户信息
            if ("new".equals(request.getUserType())) {
                // 散客：根据手机号创建或查找用户
                if (StringUtils.isEmpty(request.getUserPhone())) {
                    return AjaxResult.error("散客手机号不能为空");
                }
                userId = createOrFindUserByPhone(request.getUserPhone(), request.getUserName());
                if (userId == null) {
                    return AjaxResult.error("用户创建失败");
                }
            } else if ("existing".equals(request.getUserType())) {
                // 老客户：直接使用用户ID
                if (request.getUserId() == null) {
                    return AjaxResult.error("请选择用户");
                }
                userId = request.getUserId();
            } else {
                return AjaxResult.error("用户类型不正确");
            }
            
            // 3. 创建订单（带重试机制）
            PondOrder order = new PondOrder();
            order.setUserId(userId);
            order.setDeptId(request.getDeptId());
            order.setPondId(request.getPondId());
            order.setSeatId(request.getSeatId());
            order.setOrderType(request.getAppointmentSegmentId() != null ? 1 : 2); // 1-预约订单，2-直接订单
            order.setStartTime(request.getStartTime() != null ? 
                java.sql.Timestamp.valueOf(request.getStartTime()) : new Date());
            order.setAppointmentSegmentId(request.getAppointmentSegmentId());
            order.setStatus(0); // 未完成
            order.setTotalAmount(0.0);
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setDelFlag(0);
            
            int result = 0;
            // 最多尝试3次插入订单
            for (int retry = 1; retry <= 3; retry++) {
                try {
                    order.setOrderNo(generateOrderNo());
                    
                    // 打印订单对象数据
                    System.out.println("=== 创建的订单对象 (尝试第" + retry + "次) ===");
                    System.out.println("订单编号: " + order.getOrderNo());
                    System.out.println("用户ID: " + order.getUserId());
                    System.out.println("钓场ID: " + order.getDeptId());
                    System.out.println("鱼塘ID: " + order.getPondId());
                    System.out.println("钓位ID: " + order.getSeatId());
                    System.out.println("订单类型: " + order.getOrderType());
                    System.out.println("开始时间: " + order.getStartTime());
                    
                    result = pondOrderMapper.insertPondOrder(order);
                    if (result > 0) {
                        System.out.println("订单创建成功，订单编号: " + order.getOrderNo() + " (尝试第" + retry + "次)");
                        break;
                    }
                } catch (Exception e) {
                    if (e.getMessage().contains("Duplicate entry") && retry < 3) {
                        System.out.println("订单编号重复，重试第" + retry + "次: " + e.getMessage());
                        continue;
                    } else {
                        throw e;
                    }
                }
            }
            if (result > 0) {
                // 4. 创建订单项
                if (request.getOrderItems() != null && !request.getOrderItems().isEmpty()) {
                    createOrderItems(order.getId(), request.getOrderItems());
                } else {
                    // 创建默认钓费项目
                    createDefaultFeeItem(order.getId(), request.getSeatId());
                }
                
                // 5. 更新订单总金额
                updateOrderTotalAmount(order.getId());
                
                return AjaxResult.success("订单创建成功", order.getOrderNo());
            } else {
                return AjaxResult.error("订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("订单创建异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据手机号创建或查找用户
     */
    private Long createOrFindUserByPhone(String phone, String userName) {
        try {
            // 调用系统模块的用户服务，根据手机号获取或创建用户
            R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);
            
            if (R.FAIL == userResult.getCode()) {
                System.err.println("获取用户信息失败: " + userResult.getMsg());
                return null;
            }
            
            LoginUser loginUser = userResult.getData();
            if (loginUser != null && loginUser.getSysUser() != null) {
                Long userId = loginUser.getSysUser().getUserId();
                System.out.println("成功获取/创建用户，用户ID: " + userId + ", 手机号: " + phone);
                return userId;
            } else {
                System.err.println("用户信息为空");
                return null;
            }
        } catch (Exception e) {
            System.err.println("创建或查找用户异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public List<OrderVO> selectOrderList(OrderQueryRequest query) {
        List<OrderVO> orderList = pondOrderMapper.selectOrderList(query);
        
        // 填充用户和部门信息
        for (OrderVO orderVO : orderList) {
            // 查询订单项（为列表也添加订单项信息）
            List<OrderVO.OrderItemVO> orderItems = pondOrderItemMapper.selectByOrderId(orderVO.getId());
            orderVO.setOrderItems(orderItems);
            
            // 实时计算订单总金额（基于订单项）
            Double realTimeTotal = pondOrderItemMapper.sumAmountByOrderId(orderVO.getId());
            if (realTimeTotal != null) {
                orderVO.setTotalAmount(realTimeTotal);
                System.out.println("订单ID: " + orderVO.getId() + ", 实时计算总金额: " + realTimeTotal);
            } else {
                orderVO.setTotalAmount(0.0);
            }
            
            // 设置状态描述
            orderVO.setStatusDesc(getStatusDesc(orderVO.getStatus()));
            
            // 设置订单类型描述
            orderVO.setOrderTypeDesc(getOrderTypeDesc(orderVO.getOrderType()));
            
            // 通过远程调用获取用户信息
            if (orderVO.getUserId() != null) {
                fillUserInfo(orderVO);
            }
            
            // 通过远程调用获取部门信息
            if (orderVO.getDeptId() != null) {
                fillDeptInfo(orderVO);
            }
        }
        
        return orderList;
    }
    
    @Override
    public OrderVO selectOrderById(Long id) {
        OrderVO orderVO = pondOrderMapper.selectOrderVOById(id);
        if (orderVO != null) {
            // 查询订单项
            List<OrderVO.OrderItemVO> orderItems = pondOrderItemMapper.selectByOrderId(id);
            orderVO.setOrderItems(orderItems);
            
            // 实时计算订单总金额（基于订单项）
            Double realTimeTotal = pondOrderItemMapper.sumAmountByOrderId(id);
            if (realTimeTotal != null) {
                orderVO.setTotalAmount(realTimeTotal);
                System.out.println("订单详情 - 订单ID: " + id + ", 实时计算总金额: " + realTimeTotal);
            } else {
                orderVO.setTotalAmount(0.0);
            }
            
            // 设置状态描述
            orderVO.setStatusDesc(getStatusDesc(orderVO.getStatus()));
            
            // 设置订单类型描述
            orderVO.setOrderTypeDesc(getOrderTypeDesc(orderVO.getOrderType()));
            
            // 通过远程调用获取用户信息
            if (orderVO.getUserId() != null) {
                fillUserInfo(orderVO);
            }
            
            // 通过远程调用获取部门信息
            if (orderVO.getDeptId() != null) {
                fillDeptInfo(orderVO);
            }
        }
        return orderVO;
    }
    
    @Override
    public PondOrder selectByOrderNo(String orderNo) {
        return pondOrderMapper.selectByOrderNo(orderNo);
    }
    
    @Override
    @Transactional
    public AjaxResult updateOrderStatus(Long id, Integer status) {
        try {
            PondOrder order = pondOrderMapper.selectOrderById(id);
            if (order == null) {
                return AjaxResult.error("订单不存在");
            }
            
            order.setStatus(status);
            order.setUpdateTime(new Date());
            
            int result = pondOrderMapper.updatePondOrder(order);
            return result > 0 ? AjaxResult.success("状态更新成功") : AjaxResult.error("状态更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("状态更新异常：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public AjaxResult completeOrder(Long id) {
        return updateOrderStatus(id, 1); // 1-已完成
    }
    
    @Override
    @Transactional
    public AjaxResult cancelOrder(Long id, String reason) {
        return updateOrderStatus(id, 2); // 2-已取消
    }
    
    @Override
    @Transactional
    public AjaxResult deleteOrder(Long id) {
        try {
            // 1. 删除订单项
            pondOrderItemMapper.deleteByOrderId(id);
            
            // 2. 删除订单
            int result = pondOrderMapper.deletePondOrderById(id);
            return result > 0 ? AjaxResult.success("订单删除成功") : AjaxResult.error("订单删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("订单删除异常：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public AjaxResult deleteOrders(String ids) {
        try {
            if (StringUtils.isEmpty(ids)) {
                return AjaxResult.error("订单ID不能为空");
            }
            
            // 解析ID字符串
            String[] idArray = ids.split(",");
            List<Long> orderIds = new ArrayList<>();
            
            for (String idStr : idArray) {
                try {
                    Long id = Long.parseLong(idStr.trim());
                    orderIds.add(id);
                } catch (NumberFormatException e) {
                    return AjaxResult.error("订单ID格式错误：" + idStr);
                }
            }
            
            if (orderIds.isEmpty()) {
                return AjaxResult.error("没有有效的订单ID");
            }
            
            int successCount = 0;
            int failCount = 0;
            List<String> failedIds = new ArrayList<>();
            
            // 逐个删除订单
            for (Long orderId : orderIds) {
                try {
                    // 1. 删除订单项
                    pondOrderItemMapper.deleteByOrderId(orderId);
                    
                    // 2. 删除订单
                    int result = pondOrderMapper.deletePondOrderById(orderId);
                    if (result > 0) {
                        successCount++;
                    } else {
                        failCount++;
                        failedIds.add(String.valueOf(orderId));
                    }
                } catch (Exception e) {
                    failCount++;
                    failedIds.add(String.valueOf(orderId));
                    System.err.println("删除订单失败，订单ID: " + orderId + ", 错误: " + e.getMessage());
                }
            }
            
            // 返回删除结果
            if (failCount == 0) {
                return AjaxResult.success("批量删除成功，共删除 " + successCount + " 条订单");
            } else if (successCount == 0) {
                return AjaxResult.error("批量删除失败，失败的订单ID: " + String.join(",", failedIds));
            } else {
                return AjaxResult.success("批量删除部分成功，成功 " + successCount + " 条，失败 " + failCount + " 条，失败的订单ID: " + String.join(",", failedIds));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("批量删除异常：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public AjaxResult addOrderItem(Long orderId, CreateOrderRequest.OrderItemRequest request) {
        try {
            PondOrderItem item = new PondOrderItem();
            item.setOrderId(orderId);
            item.setItemType(request.getItemType());
            item.setItemName(request.getItemName());
            item.setAmount(request.getAmount());
            item.setPayType(request.getPayType());
            item.setPayStatus(request.getPayStatus());
            if (request.getPayStatus() == 1) {
                item.setPayTime(new Date());
            }
            item.setCreateTime(new Date());
            item.setDelFlag(0);
            
            int result = pondOrderItemMapper.insertPondOrderItem(item);
            if (result > 0) {
                // 更新订单总金额
                updateOrderTotalAmount(orderId);
                return AjaxResult.success("订单项添加成功");
            } else {
                return AjaxResult.error("订单项添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("订单项添加异常：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public AjaxResult updateOrderItemPayStatus(Long itemId, Integer payStatus, Integer payType) {
        try {
            PondOrderItem item = pondOrderItemMapper.selectPondOrderItemById(itemId);
            if (item == null) {
                return AjaxResult.error("订单项不存在");
            }
            
            item.setPayStatus(payStatus);
            item.setPayType(payType);
            if (payStatus == 1) {
                item.setPayTime(new Date());
            }
            
            int result = pondOrderItemMapper.updatePondOrderItem(item);
            return result > 0 ? AjaxResult.success("支付状态更新成功") : AjaxResult.error("支付状态更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("支付状态更新异常：" + e.getMessage());
        }
    }
    
    @Override
    public synchronized String generateOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String prefix = "ORD" + dateStr;
        
        // 最多尝试10次生成唯一编号
        for (int attempt = 1; attempt <= 10; attempt++) {
            try {
                // 查询当天已有的最大订单编号
                String maxOrderNo = pondOrderMapper.selectMaxOrderNoByPrefix(prefix);
                
                long sequence = 1;
                if (maxOrderNo != null && maxOrderNo.startsWith(prefix)) {
                    try {
                        // 提取序号部分并加1
                        String sequenceStr = maxOrderNo.substring(prefix.length());
                        sequence = Long.parseLong(sequenceStr) + 1;
                    } catch (Exception e) {
                        System.err.println("解析订单编号序号失败: " + maxOrderNo + ", 使用默认序号1");
                        sequence = 1;
                    }
                }
                
                String orderNo = prefix + String.format("%06d", sequence);
                
                // 检查生成的编号是否已存在（包括已删除的记录）
                int existsCount = pondOrderMapper.checkOrderNoExists(orderNo);
                if (existsCount == 0) {
                    System.out.println("成功生成订单编号: " + orderNo + " (尝试第" + attempt + "次)");
                    return orderNo;
                } else {
                    System.out.println("订单编号已存在: " + orderNo + ", 尝试第" + attempt + "次");
                    // 如果编号已存在，在序号基础上加上尝试次数
                    sequence += attempt;
                    orderNo = prefix + String.format("%06d", sequence);
                    existsCount = pondOrderMapper.checkOrderNoExists(orderNo);
                    if (existsCount == 0) {
                        System.out.println("调整后生成订单编号: " + orderNo);
                        return orderNo;
                    }
                }
            } catch (Exception e) {
                System.err.println("生成订单编号异常，尝试第" + attempt + "次: " + e.getMessage());
            }
        }
        
        // 如果所有尝试都失败，使用时间戳作为后缀
        long timestamp = System.currentTimeMillis() % 1000000;
        String fallbackOrderNo = prefix + String.format("%06d", timestamp);
        System.out.println("使用时间戳生成订单编号: " + fallbackOrderNo);
        return fallbackOrderNo;
    }
    
    /**
     * 创建默认钓费项目
     */
    private void createDefaultFeeItem(Long orderId, Long seatId) {
        PondOrderItem feeItem = new PondOrderItem();
        feeItem.setOrderId(orderId);
        feeItem.setItemType("fee");
        feeItem.setItemName("钓费");
        
        // 根据钓位获取钓费价格
        Double feeAmount = getSeatFeeAmount(seatId);
        feeItem.setAmount(feeAmount);
        
        feeItem.setPayType(null);
        feeItem.setPayStatus(0);
        feeItem.setCreateTime(new Date());
        feeItem.setDelFlag(0);
        
        pondOrderItemMapper.insertPondOrderItem(feeItem);
    }
    
    /**
     * 根据钓位获取钓费价格
     */
    private Double getSeatFeeAmount(Long seatId) {
        if (seatId == null) {
            return 0.0; // 默认钓费为0
        }
        
        try {
            // 根据钓位ID查询钓位信息（已包含价格段的价格）
            PondSeat seat = pondSeatMapper.selectPondSeatById(seatId);
            if (seat != null && seat.getPrice() != null && seat.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                System.out.println("获取钓位价格 - 钓位ID: " + seatId + ", 价格: " + seat.getPrice());
                return seat.getPrice().doubleValue();
            }
            
            System.out.println("钓位价格为空，使用默认价格 - 钓位ID: " + seatId);
            return 0.0; // 默认钓费为0
        } catch (Exception e) {
            System.err.println("获取钓位钓费失败: " + e.getMessage());
            return 0.0; // 异常时默认钓费为0
        }
    }
    
    /**
     * 创建订单项
     */
    private void createOrderItems(Long orderId, List<CreateOrderRequest.OrderItemRequest> requests) {
        List<PondOrderItem> items = new ArrayList<>();
        for (CreateOrderRequest.OrderItemRequest request : requests) {
            PondOrderItem item = new PondOrderItem();
            item.setOrderId(orderId);
            item.setItemType(request.getItemType());
            item.setItemName(request.getItemName());
            item.setAmount(request.getAmount());
            item.setPayType(request.getPayType());
            item.setPayStatus(request.getPayStatus());
            if (request.getPayStatus() == 1) {
                item.setPayTime(new Date());
            }
            item.setCreateTime(new Date());
            item.setDelFlag(0);
            items.add(item);
        }
        
        if (!items.isEmpty()) {
            pondOrderItemMapper.insertBatch(items);
        }
    }
    
    /**
     * 更新订单总金额
     */
    private void updateOrderTotalAmount(Long orderId) {
        Double totalAmount = pondOrderItemMapper.sumAmountByOrderId(orderId);
        if (totalAmount == null) {
            totalAmount = 0.0;
        }
        
        PondOrder order = pondOrderMapper.selectOrderById(orderId);
        if (order != null) {
            order.setTotalAmount(totalAmount);
            order.setUpdateTime(new Date());
            pondOrderMapper.updatePondOrder(order);
        }
    }
    
    /**
     * 获取状态描述
     */
    private String getStatusDesc(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 0:
                return "未完成";
            case 1:
                return "已完成";
            case 2:
                return "已取消";
            default:
                return "未知";
        }
    }
    
    /**
     * 获取订单类型描述
     */
    private String getOrderTypeDesc(Integer orderType) {
        if (orderType == null) {
            return "未知";
        }
        switch (orderType) {
            case 1:
                return "预约订单";
            case 2:
                return "直接订单";
            default:
                return "未知";
        }
    }
    
    /**
     * 填充用户信息
     */
    private void fillUserInfo(OrderVO orderVO) {
        try {
            // 调用系统模块获取用户信息
            R<List<SysUser>> userResult = remoteUserService.getUserBatch(
                java.util.Arrays.asList(orderVO.getUserId()), SecurityConstants.INNER);
            
            if (R.SUCCESS == userResult.getCode() && userResult.getData() != null && !userResult.getData().isEmpty()) {
                SysUser user = userResult.getData().get(0);
                orderVO.setUserName(user.getNickName());
                orderVO.setUserPhone(user.getPhonenumber());
                System.out.println("成功获取用户信息 - 用户ID: " + orderVO.getUserId() + 
                    ", 用户名: " + orderVO.getUserName() +
                    ", 手机号: " + orderVO.getUserPhone());
            } else {
                // 如果远程调用失败，设置默认值
                orderVO.setUserName("用户" + orderVO.getUserId());
                orderVO.setUserPhone("138****" + (orderVO.getUserId() % 10000));
                System.out.println("远程调用失败，使用默认值 - 用户ID: " + orderVO.getUserId());
            }
        } catch (Exception e) {
            System.err.println("获取用户信息失败: " + e.getMessage());
            // 异常时设置默认值
            orderVO.setUserName("用户" + orderVO.getUserId());
            orderVO.setUserPhone("138****" + (orderVO.getUserId() % 10000));
        }
    }
    
    /**
     * 填充部门信息
     */
    private void fillDeptInfo(OrderVO orderVO) {
        try {
            // TODO: 调用系统模块获取部门信息
            // 暂时设置默认值，后续可以通过远程调用获取真实部门名称
            orderVO.setDeptName("钓场" + orderVO.getDeptId());
        } catch (Exception e) {
            System.err.println("获取部门信息失败: " + e.getMessage());
            orderVO.setDeptName("钓场" + orderVO.getDeptId());
        }
    }
}